package logic

import (
	"context"
	"edu/edurpc/edurpc"
	"edu/edurpc/internal/svc"
	"edu/models/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectLogic {
	return &CollectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CollectLogic) Collect(in *edurpc.CollectRequest) (*edurpc.CollectResponse, error) {
	var collect mysql.Collect
	var status bool
	tx := mysql.DB.Begin()
	tx.Where("user_id = ?", in.UserId).Where("novel_id = ?", in.NovelId).First(&collect)
	if collect.ID != 0 {
		err := tx.Delete(&mysql.Collect{}, collect.ID).Error
		if err != nil {
			tx.Rollback()
			return nil, err
		}
		status = false
	} else {
		collect = mysql.Collect{
			UserId:  int(in.UserId),
			NovelId: int(in.NovelId),
		}
		err := tx.Create(&collect).Error
		if err != nil {
			tx.Rollback()
			return nil, err
		}
		status = true
	}
	tx.Commit()
	return &edurpc.CollectResponse{
		CollectId: int64(collect.ID),
		Status:    status,
	}, nil
}
